package de.tum.in.eist.im.client.GUIwidgets;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

import de.tum.in.eist.im.client.GUI;
import de.tum.in.eist.im.shared.User;

public class UserOnline extends GUIwidget {
	// UserList widgets (top to bottom)
	private SuggestBox suggestUserBox;

	// #Wrapper Panel
	private ScrollPanel scrollPanelUserOnline;
	private LinkedList<String> userOnlineStringList = new LinkedList<String>();
	private CellList<String> userOnlineCellList;

	private String selected = "";

	public UserOnline(GUI parent) {
		setGUIandRootPanel(parent);

		suggestUserBox = new SuggestBox();
		suggestUserBox.setSize("171px", "18px");

		scrollPanelUserOnline = new ScrollPanel();
		scrollPanelUserOnline.setSize("181px", "510px");
		userOnlineCellList = new CellList<String>(new TextCell());
		userOnlineCellList.setSize("181px", "510px");
		scrollPanelUserOnline.setWidget(userOnlineCellList);

		addHandlersToWidgets();
	}

	private void addHandlersToWidgets() {
		final SingleSelectionModel<String> selectString = new SingleSelectionModel<String>();
		selectString
				.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
					public void onSelectionChange(SelectionChangeEvent event) {
						selected = selectString.getSelectedObject();
					}
				});

		userOnlineCellList.setSelectionModel(selectString);
	}

	public void show() {
		rootPanel.add(suggestUserBox, 809, 44);
		rootPanel.add(scrollPanelUserOnline, 809, 80);
	}

	public void hide() {
		rootPanel.remove(suggestUserBox);
		rootPanel.remove(scrollPanelUserOnline);
	}

	public void init(List<User> userList) {
		for (User user : userList) {
			addUser(user);
		}
		userOnlineCellList.setRowData(userOnlineStringList);
	}

	public synchronized void addUser(User user) {
		if (!userOnlineStringList.contains(user.getUsername())) {
			userOnlineStringList.add(user.getUsername());
			userOnlineCellList.setRowData(userOnlineStringList);
		}
	}

	public void removeUser(User user) {
		userOnlineStringList.remove(user.getUsername());
		userOnlineCellList.setRowData(userOnlineStringList);
	}

	public String getSelection() {
		return selected;
	}
}
